#
# example016.py
#
# Watermarking by using LSB plus G711 A-Law compatible
#
# Copyright (C) 2012 Robert Buj Gelonch
# Copyright (C) 2012 David Megias Jimenez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
__author__ = "Robert Buj Gelonch, and David Megias Jimenez"
__copyright__ = "Copyright 2012, Robert Buj Gelonch and David Megias Jimenez"
__credits__ = ["Robert Buj Gelonch", "David Megias Jimenez"]
__license__ = "GPL"
__version__ = "3"
__maintainer__ = "Robert Buj"
__email__ = "rbuj@uoc.edu"
__status__ = "Development"
__docformat__ = 'plaintext'

import sys
import time

import getopt
from numpy import int16
from scipy.io.wavfile import read
from scipy.io.wavfile import write
from scipy.spatial.distance import chebyshev
from scipy.spatial.distance import euclidean
from scipy.stats import pearsonr
from uoc.wave.comparasion.euclidean import euclidean_similitude
from uoc.wave.comparasion.snr import snr
from uoc.wave.g711 import alaw_compression
from uoc.wave.g711 import alaw_expand
from uoc.wave.quantification import linear_quantification
from uoc.wave.watermark.message import bitarrray
from uoc.wave.watermark.schemes import lsb as WS
from uoc.wave.watermark.schemes.generic import detection_function
from uoc.wave.watermark.schemes.generic import embedding_function
from uoc.wave.watermark.schemes.generic import retrieval_function

#--------------------------------------------------------------
# Parameters of the watermarking
#--------------------------------------------------------------
M = "hello!" # secret message in the watermark, string

def example016(inputfile):
    print "example016.py"
    print
    print "WS: Linear quantification of the signal, from 16 to 13 bit ..."
    print "WS: signed precission, then G711 A-Low quantification, next..."
    print "WS: watermark inside  the mantissa by  using the LSB water-..."
    print "WS: marking scheme"
    print
    #--------------------------------------------------------------
    # Read an audio file
    #--------------------------------------------------------------
    (sample_rate, S_orig) = read(inputfile)
    #--------------------------------------------------------------
    # Linear quantification: 16 bit-signed to 13 bit-signed precission
    #--------------------------------------------------------------
    start = time.clock()
    S_quantification = linear_quantification(S_orig, (2 ** ((16-1) - 1))-1, (2 ** ((13-1) - 1))-1)
    print 'Time elapsed quantification = ', time.clock() - start, 's'
    #--------------------------------------------------------------
    # G711 A-LAW compression
    #--------------------------------------------------------------
    start = time.clock()
    (g711_mantissa, g711_exponent, g711_sign) = alaw_compression(S_quantification)
    print 'Time elapsed A-Law compression = ', time.clock() - start, 's'
    #--------------------------------------------------------------
    # Add the watermark
    #--------------------------------------------------------------
    start = time.clock()
    s_mantissa = embedding_function(g711_mantissa, \
                                    bitarrray(M), \
                                    watermarking_sheme=WS.embedding_function, \
                                    frame_size=4)
    print 'Time elapsed E = ', time.clock() - start, 's'
    #--------------------------------------------------------------
    # Identify the message
    #--------------------------------------------------------------
    start = time.clock()
    m = retrieval_function(s_mantissa, \
                           watermarking_sheme=WS.retrieval_function, \
                           frame_size=4)
    print 'Time elapsed R = ', time.clock() - start, 's'
    #--------------------------------------------------------------
    # Detection
    #--------------------------------------------------------------
    start = time.clock()
    d = detection_function(s_mantissa, \
                           bitarrray(M), \
                           watermarking_sheme=WS.detection_function, \
                           frame_size=4, \
                           message=m)
    print 'Time elapsed D = ', time.clock() - start, 's [', d, ']'
    #--------------------------------------------------------------
    # Expand A-LOW compression
    #--------------------------------------------------------------
    start = time.clock()
    s_expaded = alaw_expand(s_mantissa, g711_exponent, g711_sign)
    print 'Time elapsed A-Law expand = ', time.clock() - start, 's'
    #--------------------------------------------------------------
    # Linear quantification: 13 bit-signed to 16 bit-signed precission
    #--------------------------------------------------------------
    start = time.clock()
    s_quantification = linear_quantification(s_expaded, \
                                             (2 ** ((13-1) - 1))-1, (2 ** ((16-1) - 1))-1)
    print 'Time elapsed quantification = ', time.clock() - start, 's'
    write("../example016.E.wav", \
          sample_rate, \
          s_quantification.astype(int16))
    #--------------------------------------------------------------
    # Transparency Evaluation: SNR
    #--------------------------------------------------------------
    start = time.clock()
    snr_value = snr(S_orig, s_quantification)
    print 'Time elapsed SNR = ', time.clock() - start, 's, [', snr_value, 'dB ]'
    #--------------------------------------------------------------
    # Transparency Evaluation: Chebyshev distance
    #--------------------------------------------------------------
    start = time.clock()
    chebyshev_distance = chebyshev(S_orig, s_quantification)
    print 'Time elapsed Chebyshev distance = ', time.clock() - start, 's [', chebyshev_distance, ']'
    #--------------------------------------------------------------
    # Transparency Evaluation: Euclidian distance
    #--------------------------------------------------------------
    start = time.clock()
    euclidean_D = euclidean(S_orig, s_quantification)
    print 'Time elapsed Euclidean distance = ', time.clock() - start, 's, [', euclidean_D, ']'
    #--------------------------------------------------------------
    # Transparency Evaluation: Euclidian similitude
    #--------------------------------------------------------------
    start = time.clock()
    euclidean_S = euclidean_similitude(S_orig, s_quantification)
    print 'Time elapsed Euclidian similitude = ', time.clock() - start, 's, [', euclidean_S, ']'
    #--------------------------------------------------------------
    # Transparency Evaluation: Pearson Coeff
    #--------------------------------------------------------------
    start = time.clock()
    pearson_coeff = pearsonr(S_orig, s_quantification)
    print 'Time elapsed Pearson Coeff = ', time.clock() - start, 's [', pearson_coeff, ']'

def main(argv):
    inputfile = '../../../media/OSR_uk_000_0020_8k.wav'
    try:
        opts, args = getopt.getopt(argv, "hi:o:", ["ifile="])
    except getopt.GetoptError:
        print 'example016.py -i <inputfile>'
        sys.exit(2)
    for opt, arg in opts:
        if opt == '-h':
            print 'example016.py -i <inputfile>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
    example016(inputfile)

if __name__ == "__main__":
    main(sys.argv[1:])
    print "Done"